package rootpackege.spring.controller.websocket;

import java.security.Principal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
/**
 * 在应用的任意地方 发送消息
 * @author BriansPC
 *
 */
@Service
public class STOMPWebsocketService {

	/**
	 * 源码中  
	 * public class SimpMessagingTemplate extends AbstractMessageSendingTemplate<String>
		implements SimpMessageSendingOperations {...}
		
		因此这里将SimpMessagingTemplate对象注入到SimpMessageSendingOperations接口中
	 */
	@Autowired
	private SimpMessageSendingOperations  simpMessagingTemplate;
	
	public void sendMsg2Client(String msg){
		simpMessagingTemplate.convertAndSend("/topic/responseMsgs", "通过simpMessagingTemplate发送的数据"+msg+"......");
	}
	
	/**
	 * convertAndSendToUser()方法  将消息返回给指定用户
	 * @param principal 
	 * @param msg
	 */
	public void sendMsg2User(Principal principal,String msg){
		String username = principal.getName();
		System.out.println("username"+username);
		simpMessagingTemplate.convertAndSendToUser(username, "/queue/notifications","针对用户返回的信息"+username);
	}
}
